package com.amphiprion.prototype;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.KeyEvent;

import com.amphiprion.prototype.control.ControlerState;
import com.amphiprion.prototype.control.TouchControler;
import com.amphiprion.prototype.util.BitmapUtil;

public abstract class GameActivity extends Activity {
	private volatile boolean running;
	private GameView view;
	private long timer;

	protected abstract int getReferenceWidth();

	protected abstract int getReferenceHeight();

	protected abstract void defineBitmapOptimizations();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		view = new GameView(this);
		setContentView(view);

		if (!BitmapUtil.isInitialized()) {
			Display display = getWindowManager().getDefaultDisplay();
			int width = display.getWidth();
			int height = display.getHeight();

			BitmapUtil.init(getReferenceWidth(), getReferenceHeight(), width, height);
			defineBitmapOptimizations();

		}
		final TouchControler tc = new TouchControler(view);

		final Handler gameLoopHandler = new Handler();
		timer = System.currentTimeMillis();
		Runnable gameLoop = new Runnable() {

			@Override
			public void run() {
				// running = true;
				// long timer = System.currentTimeMillis();
				// long drawtimer = System.currentTimeMillis();

				// while (running) {
				// if (!view.drawing) {
				ControlerState state = tc.getControlerState();
				long newtimer = System.currentTimeMillis();
				// Log.d(ApplicationConstants.PACKAGE, "rnuu:" + (newtimer -
				// timer));
				view.onInput(state, newtimer - timer);
				timer = newtimer;
				// if (newtimer - drawtimer >= 30) {
				// drawtimer = newtimer;
				// runOnUiThread(new Runnable() {
				// @Override
				// public void run() {
				// view.invalidate();
				view.postInvalidate();
				// }
				// });

				// }
				// }
				// try {
				// Thread.sleep(10);
				// } catch (InterruptedException e) {
				// }
				if (running) {
					gameLoopHandler.post(this);
				}
				// }
			}
		};
		running = true;
		gameLoopHandler.post(gameLoop);
		// new Thread(gameLoop).start();
	}

	public void addScreen(GameScreen screen) {
		view.addScreen(screen);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean ret = false;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ret = view.onBackRequested();
		}
		if (ret) {
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
